package cloud.xuxiaowei.passport.controller;

import cloud.xuxiaowei.utils.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.web.csrf.CsrfFilter;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author xuxiaowei
 * @since 0.0.1
 */
@Slf4j
@RestController
@RequestMapping("/csrf")
public class CsrfTokenRestController {

	/**
	 * @see CsrfFilter
	 */
	@RequestMapping
	public Response<?> csrf(HttpServletRequest request, HttpServletResponse response, CsrfToken csrfToken) {

		// 用于创建 Session，因为默认使用的是基于 Session 的 CSRF
		HttpSession session = request.getSession();
		log.info(session.getId());

		response.addCookie(new Cookie("name-1", UUID.randomUUID().toString()));
		response.addCookie(new Cookie("name-2", UUID.randomUUID().toString()));

		String token = csrfToken.getToken();
		String headerName = csrfToken.getHeaderName();
		String parameterName = csrfToken.getParameterName();

		Map<String, Object> map = new HashMap<>();
		map.put("token", token);
		map.put("headerName", headerName);
		map.put("parameterName", parameterName);

		return Response.ok().setData(map);
	}

}
